<?php
namespace Admin\Controller;

use Common\Controller\AdminbaseController;

class UserController extends AdminbaseController{

	protected $users_model,$role_model,$logistics_model,$sale_model,$m_sale_manager;

	public $submodel = '4,8,9,10,11,12,13';

	public function _initialize() {
		parent::_initialize();
		$this->users_model = D("Common/Users");
		$this->role_model = D("Common/Role");
        $this->logistics_model  = D("Admin/Logistics");
        $this->sale_model  = D("Admin/Sale");
		$this->m_sale_manager= D("Admin/SaleManager");
	}

	// 管理员列表
	public function index(){

		$where = array("user_type"=>1, "model"=>array('not in', $this->submodel));

		/**搜索条件**/
		$user_login = I('request.user_login');
		$model = I('request.model');
		$user_email = trim(I('request.user_email'));
		if($user_login){
			$where['user_login'] = array('like',"%$user_login%");
		}
		if($model){
			$where['model'] = $model;
		}

		if($user_email){
			$where['user_email'] = array('like',"%$user_email%");;
		}
		$where["id"] = array("NOT IN",array(1,session("ADMIN_ID")));

		if($this->user_model == 4){
			$where["model"] = array("IN",array(2,3,6));
		}
//        if(session('ADMIN_ID') != 10){
//            $where["id"] = session("ADMIN_ID");
//        }
		if (session('ADMIN_ID') == '10') {
			$count=$this->users_model->withTrashed()->where($where)->count();
		}else{
			$count=$this->users_model->where($where)->count();
		}

		$page = $this->page($count, 20);
        $users = $this->users_model->where($where)->order("create_time DESC")->limit($page->firstRow, $page->listRows);

        // 如果是管理员可以看到删除的
        if (session('ADMIN_ID') == '10') {
			$users = $users->withTrashed()->order("delete_time ASC,create_time DESC");
        }

		$users = $users->select();

		foreach($users AS &$uitem){
			if($uitem['model'] == 2){
				$logistics = $this->logistics_model->where(array("id"=>$uitem['organize_id']))->find();
				$uitem['organize_name'] = $logistics['logistics_name'];
			}elseif($uitem['model'] == 3){
				$sale = $this->sale_model->where(array("id"=>$uitem['organize_id']))->find();
				$uitem['organize_name'] = $sale['sale_name'];
			}elseif($uitem['model'] == 6){
				$sale_manager = $this->m_sale_manager->where(array("id"=>$uitem['organize_id']))->find();
				$uitem['organize_name'] = $sale_manager['sale_manage_name'];
			}elseif($uitem['model'] == 7){
				$logistics = $this->logistics_model->where(array("id"=>$uitem['organize_id'],'manager_id'=>array('neq',0)))->find();
				$uitem['organize_name'] = $logistics['logistics_name'];
			}else{
				$uitem['organize_name'] = '管理员';
			}
		}
		$roles_src=$this->role_model->where(array("id"=>array('not in', $this->submodel)))->select();
		$roles=array();
		foreach ($roles_src as $r){
			$roleid=$r['id'];
			$roles["$roleid"]=$r;
		}
		$this->assign("page", $page->show('Admin'));
		$this->assign("roles",$roles);
		$this->assign("users",$users);
		$this->display();
	}

	// 管理员列表
	public function index_sub(){

		$where = array("user_type"=>1, "model"=>array('in', $this->submodel));
		/**搜索条件**/
		$user_login = I('request.user_login');
		$model = I('request.model');
		$user_email = trim(I('request.user_email'));
		if($user_login){
			$where['user_login'] = array('like',"%$user_login%");
		}
		if($model){
			$where['model'] = $model;
		}

		if($user_email){
			$where['user_email'] = array('like',"%$user_email%");;
		}
		$where["id"] = array("NOT IN",array(1,session("ADMIN_ID")));

		if($this->user_model == 4){
			$where["model"] = array("IN",array(2,3,6));
		}
//        if(session('ADMIN_ID') != 10){
//            $where["id"] = session("ADMIN_ID");
//        }
		if (session('ADMIN_ID') == '10') {
			$count=$this->users_model->withTrashed()->where($where)->count();
		}else{
			$count=$this->users_model->where($where)->count();
		}

		$page = $this->page($count, 20);
        $users = $this->users_model->where($where)->order("create_time DESC")->limit($page->firstRow, $page->listRows);

        // 如果是管理员可以看到删除的
        if (session('ADMIN_ID') == '10') {
			$users = $users->withTrashed()->order("delete_time ASC,create_time DESC");
        }

		$users = $users->select();

		foreach($users AS &$uitem){
			if($uitem['model'] == 2){
				$logistics = $this->logistics_model->where(array("id"=>$uitem['organize_id']))->find();
				$uitem['organize_name'] = $logistics['logistics_name'];
			}elseif($uitem['model'] == 3){
				$sale = $this->sale_model->where(array("id"=>$uitem['organize_id']))->find();
				$uitem['organize_name'] = $sale['sale_name'];
			}elseif($uitem['model'] == 6){
				$sale_manager = $this->m_sale_manager->where(array("id"=>$uitem['organize_id']))->find();
				$uitem['organize_name'] = $sale_manager['sale_manage_name'];
			}elseif($uitem['model'] == 7){
				$logistics = $this->logistics_model->where(array("id"=>$uitem['organize_id'],'manager_id'=>array('neq',0)))->find();
				$uitem['organize_name'] = $logistics['logistics_name'];
			}else{
				$uitem['organize_name'] = '管理员';
			}
		}
		$roles_src=$this->role_model->where(array('id'=> array('in', $this->submodel)))->select();
		$roles=array();
		foreach ($roles_src as $r){
			$roleid=$r['id'];
			$roles["$roleid"]=$r;
		}
		$this->assign("page", $page->show('Admin'));
		$this->assign("roles",$roles);
		$this->assign("users",$users);
		$this->display();
	}

	// 管理员添加
	public function add(){
		$where = array('status' => 1);

		if($this->user_model == 5){
			$where["id"] = array("IN",array(2,3,4,6,7));
		}else{
			$where["id"] = array("IN",array(2,3,6,7));
		}

		$roles=$this->role_model->where($where)->order("listorder DESC")->select();
		$this->assign("roles",$roles);
        //获取物流公司 及 消费平台
        $logistics_list = $this->logistics_model->where(array('manager_id'=>0))->select();
        $logistics_sub_list = $this->logistics_model->where(array('manager_id'=>array('neq',0)))->select();
        $sale_list = $this->sale_model->select();
        $this->assign("logistics_list",$logistics_list);
        $this->assign("logistics_sub_list",$logistics_sub_list);
        $this->assign("sale_list",$sale_list);
		//获取消费机构管理员
		$sale_manager_list = $this->m_sale_manager->select();
		$this->assign("sale_manager_list",$sale_manager_list);
		$this->display();
	}

	// 管理员添加
	public function add_sub(){
		$where = array('status' => 1);

		$where["id"] = array("IN", $this->submodel);

		$roles=$this->role_model->where($where)->order("listorder DESC")->select();
		$this->assign("roles",$roles);
		$this->display();
	}

	// 管理员添加提交
	public function add_post(){
		if(IS_POST){
			if(empty($_POST["user_nicename"])){
				$this->error("姓名不能为空！");exit;
			}
			if(empty($_POST["user_phone"])){
				$this->error("手机号不能为空！");exit;
			}
			if ($_POST['model'] == 2){
				$_POST['organize_id'] = $_POST['organize_id1'];
				if(empty($_POST['organize_id'])){
					$this->error("请选择绑定的物流公司！");exit;
				}
			}elseif($_POST['model'] == 3){
				$_POST['organize_id'] = $_POST['organize_id2'];
				if(empty($_POST['organize_id'])){
					$this->error("请选择绑定的消费机构！");exit;
				}
			}elseif($_POST["model"] == 6){
				$_POST['organize_id'] = $_POST['organize_id3'];
				if(empty($_POST['organize_id'])){
					$this->error("请选择绑定的二级物流公司！");exit;
				}
			}elseif($_POST["model"] == 7){
				$_POST['organize_id'] = $_POST['organize_id4'];
				if(empty($_POST['organize_id'])){
					$this->error("请选择绑定的上级消费机构！");exit;
				}
			}
			$_POST['role_id'] = array($_POST['role_id']);
			if(!empty($_POST['role_id']) && is_array($_POST['role_id'])){
				$role_ids=$_POST['role_id'];
				unset($_POST['role_id']);
				if ($this->users_model->create()!==false) {
					$result=$this->users_model->add();
					if ($result!==false) {
						$role_user_model=M("RoleUser");
						foreach ($role_ids as $role_id){
							if(sp_get_current_admin_id() != 1 && $role_id == 1){
								$this->error("为了网站的安全，非网站创建者不可创建超级管理员！");
							}
							$role_user_model->add(array("role_id"=>$role_id,"user_id"=>$result));
						}
						$this->success("添加成功！");
					} else {
						$this->error("添加失败！");
					}
				} else {
					$this->error($this->users_model->getError());
				}
			}else{
				$this->error("请为此用户指定角色！");
			}

		}
	}

	// 管理员编辑
	public function edit(){
	    $id = I('get.id',0,'intval');
		$where = array('status' => 1);
		if($this->user_model == 5){
			$where["id"] = array("IN",array(2,3,4,6));
		}else{
			$where["id"] = array("IN",array(2,3,6));
		}
		$roles=$this->role_model->where($where)->order("id DESC")->select();
		$this->assign("roles",$roles);
		$role_user_model=M("RoleUser");
		$role_ids=$role_user_model->where(array("user_id"=>$id))->getField("role_id",true);
		$this->assign("role_ids",$role_ids);

		$user=$this->users_model->where(array("id"=>$id))->find();
		$this->assign($user);

		//获取物流公司 及 消费平台
		$logistics_list = $this->logistics_model->select();
		$sale_list = $this->sale_model->select();
		$this->assign("logistics_list",$logistics_list);
		$this->assign("sale_list",$sale_list);
		//获取消费机构管理员
		$sale_manager_list = $this->m_sale_manager->select();
		$this->assign("sale_manager_list",$sale_manager_list);
		$this->display();
	}

	// 管理员编辑
	public function edit_sub(){
	    $id = I('get.id',0,'intval');
		$where = array('status' => 1);


		$where["id"] = array("IN", $this->submodel);

		$roles=$this->role_model->where($where)->order("id DESC")->select();
		$this->assign("roles",$roles);
		$role_user_model=M("RoleUser");
		$role_ids=$role_user_model->where(array("user_id"=>$id))->getField("role_id",true);
		$this->assign("role_ids",$role_ids);

		$user=$this->users_model->where(array("id"=>$id))->find();
		$this->assign($user);

		$this->display();
	}

	// 管理员编辑提交
	public function edit_post(){
		if (IS_POST) {
			if(empty($_POST["user_nicename"])){
				$this->error("姓名不能为空！");exit;
			}
			if(empty($_POST["user_phone"])){
				$this->error("手机号不能为空！");exit;
			}

			if($_POST['model'] == 3){
				$_POST['organize_id'] = $_POST['organize_id2'];
				if(empty($_POST['organize_id'])){
					$this->error("请选择绑定的消费机构！");exit;
				}
			}elseif($_POST['model'] == 2){
				$_POST['organize_id'] = $_POST['organize_id1'];
				if(empty($_POST['organize_id'])){
					$this->error("请选择绑定的物流公司！");exit;
				}
			}elseif($_POST["model"] == 6){
				$_POST['organize_id'] = $_POST['organize_id3'];
				if(empty($_POST['organize_id'])){
					$this->error("请选择绑定的上级消费机构！");exit;
				}
			}
			$_POST['role_id'] = array($_POST['role_id']);

			if(!empty($_POST['role_id']) && is_array($_POST['role_id'])){
				if(empty($_POST['user_pass'])){
					unset($_POST['user_pass']);
				}
				$role_ids = I('post.role_id/a');
				unset($_POST['role_id']);
				if ($this->users_model->create()!==false) {
					$result=$this->users_model->save();
					if ($result!==false) {
						$uid = I('post.id',0,'intval');
						$role_user_model=M("RoleUser");
						$role_user_model->where(array("user_id"=>$uid))->delete();
						foreach ($role_ids as $role_id){
							if(sp_get_current_admin_id() != 1 && $role_id == 1){
								$this->error("为了网站的安全，非网站创建者不可创建超级管理员！");
							}
							$role_user_model->add(array("role_id"=>$role_id,"user_id"=>$uid));
						}
						$this->success("保存成功！");
					} else {
						$this->error("保存失败！");
					}
				} else {
					$this->error($this->users_model->getError());
				}
			}else{
				$this->error("请为此用户指定角色！");
			}

		}
	}

	// 管理员删除
	public function delete(){
	    $id = I('get.id',0,'intval');
		if($id==1){
			$this->error("最高管理员不能删除！");
		}

		if ($this->users_model->delete($id)!==false) {
			// M("RoleUser")->where(array("user_id"=>$id))->delete();
			$this->success("删除成功！");
		} else {
			$this->error("删除失败！");
		}
	}

	/*彻底删除就是把软删除关了，感觉理论上应该没错*/
	public function overdelete(){
		$id = I('get.id',0,'intval');
		if($id==1){
			$this->error("最高管理员不能删除！");
		}

		// delete传参数true就是强制删除
		if ($this->users_model->delete($id,true)!==false) {
			M("RoleUser")->where(array("user_id"=>$id))->delete();
			$this->success("删除成功！");
		} else {
			$this->error("删除失败！");
		}
	}

	/*彻底删除就是把软删除关了*/
	public function restore(){
	    $id = I('get.id',0,'intval');

		$result = $this->users_model->restore($id);

		if ($result) {
			$this->success("数据已恢复！");
		}else{
			$this->success("数据恢复失败！");
		}
	}

	// 管理员个人信息修改
	public function userinfo(){
		$id=sp_get_current_admin_id();
		$user=$this->users_model->where(array("id"=>$id))->find();
		$this->assign($user);
		$this->display();
	}

	// 管理员个人信息修改提交
	public function userinfo_post(){
		if (IS_POST) {
			$_POST['id']=sp_get_current_admin_id();
			$create_result=$this->users_model
			->field("id,user_nicename,user_phone,sex,birthday,user_url,signature")
			->create();
			if ($create_result!==false) {
				if ($this->users_model->save()!==false) {
					$this->success("保存成功！");
				} else {
					$this->error("保存失败！");
				}
			} else {
				$this->error($this->users_model->getError());
			}
		}
	}

	// 停用管理员
    public function ban(){
        $id = I('get.id',0,'intval');
    	if (!empty($id)) {
    		$result = $this->users_model->where(array("id"=>$id,"user_type"=>1))->setField('user_status','0');
    		if ($result!==false) {
    			$this->success("管理员停用成功！");
    		} else {
    			$this->error('管理员停用失败！');
    		}
    	} else {
    		$this->error('数据传入失败！');
    	}
    }

    // 启用管理员
    public function cancelban(){
    	$id = I('get.id',0,'intval');
    	if (!empty($id)) {
    		$result = $this->users_model->where(array("id"=>$id,"user_type"=>1))->setField('user_status','1');
    		if ($result!==false) {
    			$this->success("管理员启用成功！");
    		} else {
    			$this->error('管理员启用失败！');
    		}
    	} else {
    		$this->error('数据传入失败！');
    	}
    }



}